package com.github.xzb617.rpc.loadbalancer.factory;

import com.github.xzb617.rpc.loadbalancer.LoadBalancer;
import java.lang.reflect.Constructor;

/**
 * 负载均衡Bean工程
 */
public class LbBeanFactory {

    /**
     * 根据策略获取负载均衡实例
     * @param loadBalancerClazz 负载均衡策略的类全路径
     * @return LoadBalancer
     */
    public static LoadBalancer getInstance(String loadBalancerClazz) throws LbBeanCreatedException {
        if (loadBalancerClazz == null) {
            throw new IllegalArgumentException("No loadBalancerClazz applied");
        }
        try
        {
            Class<?> algClazz = Class.forName(loadBalancerClazz);
            Constructor<?> constructor = algClazz.getDeclaredConstructor();
            return (LoadBalancer) constructor.newInstance();
        }
        catch (ClassNotFoundException e)
        {
            throw new LbBeanCreatedException(String.format(" [%s] can not be found, check this class path or it exists.", loadBalancerClazz));
        }
        catch (Exception e)
        {
            throw new LbBeanCreatedException("LoadBalancer bean created failure.", e);
        }
    }

}
